package com.immunology.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import com.immunology.core.BaseDao;
import com.immunology.core.BaseTransformer;
import com.immunology.core.GenericDao;
import com.immunology.database.DbColumns;
import com.immunology.model.SurveyAnswer;

public class SurveyAnswerDao extends BaseDao<SurveyAnswer> implements
		GenericDao<SurveyAnswer> {

	public SurveyAnswerDao(BaseTransformer<SurveyAnswer> transformer) {
		super(transformer, new String("SURVEY_ANSWER"));
	}

	@Override
	public void insert(SurveyAnswer surveyAnswer) {
		Connection connection = connectionManager.getConnection();
		StringBuilder query = new StringBuilder();
		query.append("INSERT INTO ");
		query.append(tableName);
		query.append(" (complaint_id, survey_id, value, description)");
		query.append(" VALUES(?, ?, ?, ?)");
		PreparedStatement preparedStatement = null;
		try {
			preparedStatement = (PreparedStatement) connection
					.prepareStatement(query.toString());
			preparedStatement.setInt(DbColumns.FIRST_COLUMN,
					surveyAnswer.getComplaintId());
			preparedStatement.setInt(DbColumns.SECOND_COLUMN,
					surveyAnswer.getSurveyId());
			preparedStatement.setInt(DbColumns.THIRD_COLUMN,
					surveyAnswer.getValue());
			preparedStatement.setString(DbColumns.FOURTH_COLUMN,
					surveyAnswer.getDescription());
			preparedStatement.executeUpdate();
			preparedStatement.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connectionManager.closeConnection(connection);
		}
	}

	@Override
	public void update(int id, SurveyAnswer obj) {
		// TODO Auto-generated method stub

	}

	public Map<Integer, Integer> getComplaintIdValueMapBySurveyId(int surveyId) {
		Map<Integer, Integer> complaintValueMap = new HashMap<Integer, Integer>();

		Connection connection = connectionManager.getConnection();
		int complaintId = 0;
		int value = 0;
		StringBuilder query = new StringBuilder();
		query.append("SELECT complaint_id, value FROM ");
		query.append(tableName);
		query.append(" WHERE survey_id = " + surveyId);
		try {
			Statement statement = connection.createStatement();
			ResultSet set = statement.executeQuery(query.toString());
			while (set.next()) {
				complaintId = set.getInt(DbColumns.FIRST_COLUMN);
				value = set.getInt(DbColumns.SECOND_COLUMN);
				complaintValueMap.put(complaintId, value);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connectionManager.closeConnection(connection);
		}
		return complaintValueMap;

	}

}
